<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>课程管理</title>
    <link rel="stylesheet" href="static/elementui.css">
    <script src="static/vue@2.6.14.js"></script>
    <script src="static/elementui.js"></script>
    <script src="static/axios.min.js"></script>
    <style>
        body {
            padding: 20px;
        }

        .toolbar {
            margin-bottom: 20px;
        }

        .dialog-footer {
            text-align: right;
        }

        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }

        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        /* 优化后的 transfer 样式 */
        .custom-transfer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 20px;
            margin: 20px 0;
        }

        .custom-transfer .el-transfer {
            display: flex;
            align-items: center;
            width: 100%;
        }

        .custom-transfer .el-transfer-panel {
            width: 40%;
            height: 400px;
        }

        .custom-transfer .el-transfer-panel__body {
            height: 340px;
        }

        .custom-transfer .el-transfer-panel__list.is-filterable {
            height: 290px;
        }

        .custom-transfer .el-transfer__buttons {
            display: flex;
            flex-direction: column;
            padding: 0 20px;
        }

        .custom-transfer .el-transfer__button {
            margin: 5px 0;
        }

        .custom-transfer .el-transfer-panel__header {
            background-color: #f5f7fa;
            padding: 12px 15px;
            font-size: 14px;
            font-weight: 500;
            color: #333;
        }

        .custom-transfer .el-transfer-panel__item {
            padding: 10px 15px;
            line-height: 1.5;
        }

        .custom-transfer .el-transfer-panel__filter {
            margin: 10px;
        }

        /* 对话框样式优化 */
        .el-dialog__body {
            padding: 20px 30px;
        }

        .el-form-item {
            margin-bottom: 22px;
        }

        .el-form-item__label {
            font-weight: 500;
            color: #333;
        }

        /* 自定义表单样式 */
        .course-form {
            max-width: 900px;
            margin: 0 auto;
        }

        .course-form .el-date-picker {
            width: 100%;
        }
    </style>
</head>
<body>
<div id="app">
    <el-card>
        <div class="toolbar">
            <el-input placeholder="搜索课程名称" v-model="searchKeyword" style="width: 200px;"></el-input>
            <el-button v-if="user.roleType === 'teacher'" type="primary" @click="handleAddCourse" size="small">
                添加课程
            </el-button>
        </div>
        <el-table :data="courses" stripe>
            <el-table-column prop="courseName" label="课程名称"></el-table-column>
            <el-table-column v-if="user.roleType === 'admin'" prop="teacherId" label="教师ID"></el-table-column>
            <el-table-column prop="startTime" label="开课时间"></el-table-column>
            <el-table-column prop="endTime" label="结课时间"></el-table-column>
            <el-table-column label="课程图片">
                <template slot-scope="scope">
                    <el-image :src="scope.row.courseImage" style="width: 50px; height: 50px"></el-image>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="180">
                <template slot-scope="scope">
                    <el-button @click="handleEdit(scope.row)" type="primary" size="small">编辑</el-button>
                    <el-button @click="handleDelete(scope.row)" type="danger" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="block">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalCourses">
            </el-pagination>
        </div>
    </el-card>

    <el-dialog title="课程信息" :visible.sync="dialogVisible" width="70%">
        <el-form :model="currentCourse" :rules="rules" ref="courseForm" label-position='top' label-width="100px"
                 class="course-form">
            <el-form-item label="课程名称" prop="courseName">
                <el-input v-model="currentCourse.courseName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="开课时间" prop="startTime">
                <el-date-picker v-model="currentCourse.startTime" type="datetime" placeholder="选择开课时间"
                                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="结课时间" prop="endTime">
                <el-date-picker v-model="currentCourse.endTime" type="datetime" placeholder="选择结课时间"
                                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="课程图片">
                <el-upload
                        class="avatar-uploader"
                        action="/upload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="课程学生管理" label-width="0">
                <div class="custom-transfer">
                    <el-transfer
                            v-model="currentCourse.studentIds"
                            :data="students"
                            filterable
                            :titles="['待选学生', '已选学生']"
                            :props="{
                                key: 'id',
                                label: 'fullname'
                            }"
                            :button-texts="['移除', '选择']">
                    </el-transfer>
                </div>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false" size="small">取消</el-button>
            <el-button type="primary" @click="handleSave" size="small">保存</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                searchKeyword: '',
                courses: [],
                totalCourses: 0,
                pageSize: 5,
                currentPage: 1,
                dialogVisible: false,
                currentCourse: {
                    studentIds: []
                },
                isEditMode: false,
                user: {},
                imageUrl: '',
                students: [],
                rules: {
                    courseName: [
                        {required: true, message: '请输入课程名称', trigger: 'blur'}
                    ],
                    startTime: [
                        {required: true, message: '请选择开课时间', trigger: 'blur'}
                    ],
                    endTime: [
                        {required: true, message: '请选择结课时间', trigger: 'blur'}
                    ]
                }
            };
        },
        watch: {
            searchKeyword(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.currentPage = 1;
                    this.fetchCourses();
                }
            },
            currentPage(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchCourses();
                }
            },
            pageSize(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchCourses();
                }
            }
        },
        methods: {
            fetchCourses() {
                const teacherId = this.user.roleType === 'teacher' ? this.user.id : null;
                axios.get('/course?operation=getCoursesByPageAndName', {
                    params: {
                        teacherId: teacherId,
                        keyword: this.searchKeyword,
                        pageNum: this.currentPage,
                        pageSize: this.pageSize
                    }
                }).then(response => {
                    const {code, data} = response.data;
                    if (code === 200) {
                        this.courses = data.list.map(course => ({
                            ...course,
                            studentIds: Array.isArray(course.studentIds)
                                ? course.studentIds
                                : (course.studentIds ? JSON.parse(course.studentIds) : [])
                        }));
                        this.totalCourses = data.total;
                    } else {
                        this.$message.error('获取课程列表失败');
                    }
                }).catch(error => {
                    console.error('获取课程列表失败:', error);
                    this.$message.error('获取课程列表失败');
                });
            },
            handleAddCourse() {
                this.isEditMode = false;
                this.currentCourse = {
                    teacherId: this.user.id,
                    studentIds: []
                };
                this.imageUrl = '';
                this.fetchStudents();
                this.dialogVisible = true;
            },
            handleEdit(course) {
                this.isEditMode = true;
                this.currentCourse = JSON.parse(JSON.stringify(course));
                this.currentCourse.studentIds = Array.isArray(course.studentIds)
                    ? course.studentIds.map(student => student.id)
                    : (course.studentIds ? JSON.parse(course.studentIds).map(student => student.id) : []);
                this.imageUrl = course.courseImage;
                this.fetchStudents();
                this.dialogVisible = true;
            },
            handleSave() {
                this.$refs.courseForm.validate(valid => {
                    if (valid) {
                        const selectedStudents = this.students
                            .filter(student => this.currentCourse.studentIds.includes(student.id))
                            .map(student => ({
                                id: student.id,
                                fullname: student.fullname
                            }));

                        const submitData = {
                            ...this.currentCourse,
                            studentIds: JSON.stringify(selectedStudents)
                        };

                        const url = this.isEditMode ? '/course?operation=updateCourse' : '/course?operation=addCourse';
                        axios.post(url, submitData)
                            .then(response => {
                                if (response.data.code === 200) {
                                    this.$message.success(this.isEditMode ? '课程信息更新成功' : '课程添加成功');
                                    this.fetchCourses();
                                    this.dialogVisible = false;
                                } else {
                                    this.$message.error(this.isEditMode ? '课程信息更新失败' : '课程添加失败');
                                }
                            })
                            .catch(error => {
                                console.error(this.isEditMode ? '课程信息更新失败:' : '课程添加失败:', error);
                                this.$message.error(this.isEditMode ? '课程信息更新失败' : '课程添加失败');
                            });
                    }
                });
            },
            handleDelete(course) {
                this.$confirm('此操作将永久删除该课程, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post('/course?operation=deleteCourse&id=' + course.id)
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('课程删除成功');
                                this.fetchCourses();
                            } else {
                                this.$message.error('课程删除失败');
                            }
                        })
                        .catch(error => {
                            console.error('课程删除失败:', error);
                            this.$message.error('课程删除失败');
                        });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            },
            handleAvatarSuccess(response, file) {
                this.imageUrl = response.data;
                this.currentCourse.courseImage = response.data;
                this.$message.success('课程图片上传成功');
            },
            beforeAvatarUpload(file) {
                return true;
            },
            handleSizeChange(val) {
                this.pageSize = val;
            },
            handleCurrentChange(val) {
                this.currentPage = val;
            },
            fetchStudents() {
                axios.get('/user?operation=findAll')
                    .then(response => {
                        const {code, data} = response.data;
                        if (code === 200) {
                            this.students = data
                                .filter(user => user.roleType === 'student')
                                .map(user => ({
                                    id: user.id,
                                    fullname: user.fullname
                                }));
                        } else {
                            this.$message.error('获取学生列表失败');
                        }
                    }).catch(error => {
                    console.error('获取学生列表失败:', error);
                    this.$message.error('获取学生列表失败');
                });
            }
        },
        mounted() {
            const userData = localStorage.getItem('user');
            if (userData) {
                this.user = JSON.parse(userData);
            }
            this.fetchCourses();
        }
    });
</script>
</body>
</html>